package xyz.archknight.app.loginput.dictionary.gen.ui

import com.hankcs.hanlp.model.crf.CRFLexicalAnalyzer
import org.jetbrains.exposed.sql.transactions.transaction
import xyz.archknight.app.loginput.dictionary.gen.dao.Cache
import xyz.archknight.app.loginput.dictionary.gen.dao.Word
import xyz.archknight.app.loginput.dictionary.gen.service.EventBus
import java.awt.BorderLayout
import java.awt.Dimension
import java.awt.FlowLayout
import javax.swing.*

/**
 * 缓存管理页面中用于进行整段文字拆分的对话框
 *
 * @author midnite
 * create at 2020-06-21 10:09 上午
 */
class DocumentImportDialog(owner: JFrame) : JDialog(owner) {
    private val textArea = JTextArea(14, 40)
    private val scrollArea = JScrollPane(textArea)
    private val operatePane = JPanel()
    private val analysisButton = JButton("分析文字")

    init {
        createUI()
    }

    private fun createUI() {
        size = Dimension(400, 320)
        contentPane = JPanel().apply {
            border = BorderFactory.createEmptyBorder(8, 8, 8, 8)
        }
        with(operatePane) {
            layout = FlowLayout(FlowLayout.RIGHT)
            add(analysisButton)
        }

        with(contentPane) {
            layout = BorderLayout(8, 8)
            add(JLabel("请把要分解的整段文字粘贴在下面"), BorderLayout.NORTH)
            add(scrollArea, BorderLayout.CENTER)
            add(operatePane, BorderLayout.SOUTH)
        }

        textArea.lineWrap = true

        analysisButton.addActionListener { analysis() }

        modalityType = ModalityType.APPLICATION_MODAL
        setLocationRelativeTo(null)
    }

    private fun analysis() {
        transaction {
            val existsWords = Word.all().map { it.phase } + Cache.all().map { it.phase }
            val inputs = textArea.text
            val analyzer = CRFLexicalAnalyzer()
            val terms = analyzer.analyze(inputs)
                .toSimpleWordList()
                .map { it.value.trim() }
                .filter { it.length > 1 }
                .filter { it !in existsWords }
                .toSet()
            terms.forEach { EventBus.sendAnalysis(it) }
        }
        isVisible = false
    }

}